<template>
  <div>
    <div style="margin-bottom: 10px; margin-left: 30px">
      <el-tag type="primary">什么是被驳回人？</el-tag>
      <el-tag type="danger"
        >当前被驳回节点下的任务需办理过或存在办理人才可驳回，否则请使用【任意跳转】</el-tag
      >
    </div>
    <el-form
      ref="dataFormRef"
      v-loading="loading"
      :model="state.form"
      :rules="dataRules"
      label-width="100px"
      :disabled="operType === 'view'"
    >
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="流程名称" prop="defFlowId">
            <el-input
              v-model="state.form.flowName"
              placeholder="流程名称"
              disabled
            />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="流程实例" prop="flowInstId">
            <el-input
              v-model="state.form.flowInstId"
              placeholder="流程实例ID"
              disabled
            />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="驳回节点" prop="toRunNodeId">
            <el-tooltip
              placement="top"
              content="若不选择具体的【指定被驳回人】，则默认会驳回到该节点下的全部办理人"
            >
              <CommonSelect
                v-model:defaultValue="state.form.toRunNodeId"
                :placeholder="translate('请选择驳回节点')"
                label="nodeName"
                value="id"
                :url="rejectNodeListUrl"
                :query-params="state.nodeParams"
                auto-query
                @change="handleToRunNodeChange"
              />
            </el-tooltip>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="指定被驳回人" prop="handleUserId">
            <el-tooltip placement="top">
              <template #content>{{
                validateNull(state.form.handleUserId) ? userIdText : userIdText2
              }}</template>
              <CommonSelect
                ref="handleUserIdRef"
                v-model:defaultValue="state.form.handleUserId"
                :placeholder="translate('请选择被驳回人')"
                label="userName"
                value="id"
                :url="nodeUserListUrl"
                auto-query
                @loaded="handleUserLoaded"
              />
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <footer class="el-dialog__footer">
      <span class="dialog-footer">
        <el-button
          type="primary"
          :loading="loading"
          :disabled="state.confirmDisable"
          @click="handleUpdate"
        >
          确认
        </el-button>
      </span>
    </footer>
  </div>
</template>

<script setup lang="ts" name="RunRejectForm">
import { translate } from "@/plugins/i18n";
import { useMessage } from "@/hooks/message";
import { validateNull } from "@/utils/validate";
import CommonSelect from "@/components/commonSelect.vue";
import { onMounted, reactive, ref, watch } from "vue";
import * as doJob from "@/api/flow/jobtask";

const $message = useMessage();
const $emit = defineEmits(["confirm"]);
// 定义变量内容
const dataFormRef = ref();
const loading = ref(false);
const operType = ref("");
const handleUserIdRef = ref(null);

const props = defineProps({
  currJob: {
    type: Object,
    default: null
  },
  comment: {
    type: String,
    default: null
  }
});

// 提交表单数据
const state = reactive({
  confirmDisable: true,
  form: {
    defFlowId: "",
    flowName: "",
    flowInstId: "",
    toRunNodeId: "",
    handleUserId: "",
    nodeType: ""
  },
  nodeParams: {
    runNodeId: props.currJob.runNodeId
  }
});

// 定义校验规则
const dataRules = ref({
  defFlowId: [{ required: true, message: "流程名称不能为空", trigger: "blur" }],
  flowInstId: [
    { required: true, message: "流程实例ID不能为空", trigger: "blur" }
  ],
  toRunNodeId: [
    { required: true, message: "达到节点名称不能为空", trigger: "blur" }
  ]
});

const userIdText =
  "注：当前被驳回节点下可候选被驳回人为空不可驳回，请使用【任意跳转】";
const userIdText2 =
  "注：当被驳回人为空时，则默认会驳回到当前节点显示的全部办理人,当被驳回人不为空时，则会驳回到该节点下指定的办理人员";

const handleUserLoaded = () => {
  nextTick(() => {
    const opt = handleUserIdRef.value.getOptions();
    if (opt && opt.length > 0) {
      state.confirmDisable = false;
    } else {
      state.confirmDisable = true;
    }
  });
};

const rejectNodeListUrl = computed(() => {
  return `/esflow/run/node/pre/${props.currJob.flowInstId}`;
});

const nodeUserListUrl = computed(() => {
  return `/esflow/run/job/list/user/${state.form.toRunNodeId}`;
});

const handleToRunNodeChange = (id, node) => {
  state.form.toRunNodeId = id;
  state.form.nodeType = node.nodeType;
};

function initJobData() {
  Object.assign(state.form, props.currJob);
  state.form.flowInstId = props.currJob.flowInstId;
  state.form.defFlowId = props.currJob.defFlowId;
  if (props.currJob.runFlow) {
    state.form.flowName = props.currJob.runFlow.flowName;
  }
}

async function handleUpdate() {
  dataFormRef.value.validate(async valid => {
    if (valid) {
      if (validateNull(state.form.handleUserId)) {
        $message.warning(userIdText);
        return;
      }
      loading.value = true;
      try {
        const params = {
          id: props.currJob.id,
          toRunNodeId: state.form.toRunNodeId,
          handleUserId: state.form.handleUserId,
          nodeType: state.form.nodeType,
          comment: props.comment
        };
        doJob.reject(params).then(res => {
          if (res.code === 200) {
            useMessage().success("驳回成功");
            $emit("confirm");
            setTimeout(() => {
              // 异步异常
              loading.value = false;
            }, 3000);
          } else {
            useMessage().error(res.msg);
          }
        });
      } catch (e) {
        loading.value = false;
      }
    }
  });
}

// 监听双向绑定
watch(
  () => props.currJob.id,
  val => {
    initJobData();
  }
);

onMounted(() => {
  initJobData();
});
</script>

<style lang="scss" scoped>
.el-dialog__footer {
  text-align: center;

  .dialog-footer {
    text-align: center;
  }
}
</style>
